import React, { useState, useEffect, useRef, useContext } from 'react';
import moment from 'moment';
import './index.less';
import Area from 'components/Area';
import { Card, Button, Drawer, notification, Modal, message } from 'antd';
import { EnvironmentOutlined, VideoCameraOutlined } from '@ant-design/icons';
import { getAllAlarms, IAlarm, checkAlarmApi } from 'api/AbnormalAlarm';
import { useRequest } from 'ahooks';
import { getLiftingControlByArea } from 'api/LiftControl';
import LiftControl from './lift-control';
import { getCameraAll, getCamerasByArea, ICamera } from 'api/Camera';
import EmptyTip from 'components/EmptyTip';
import { providerHoc, reducer, initialReducer, ProviderContext } from 'store';

const Home = () => {
    const [currentTime, setCurrentTime] = useState(''); // 当前时间
    const [selectedArea, setSelectedArea] = useState(-1); // 选中区域
    const [drawerVisible, setDrawerVisible] = useState(false); // 报警抽屉打开
    const [cameras, setCameras] = useState<ICamera[]>();
    const areaRef: any = useRef();

    const [abnormalVideoVisible, setAbnormalVideoVisible] = useState(false)
    const [abnormalData, setAbnormalData] = useState()
    /** 获取区域控制箱 */
    const { data: areaLiftControl, run: getLiftControlByAreaRun, loading: areaLiftLoading } = useRequest(
        () => getLiftingControlByArea({ areaId: selectedArea }),
        {
            manual: true,
        },
    );
    /** reducer初始化 */
    const { state, asyncActions } = useContext(ProviderContext);
    
    /** 获取报警信息 */
    const { data: alarmList, run: getAllAlarmsRun } = useRequest(getAllAlarms, {
        pollingInterval: 10000,
        onSuccess(res) {
            asyncActions.asyncSetAlarms(res)
        }
    });
    const viewVideo = (data: any) => {
        setAbnormalVideoVisible(true)
        setAbnormalData(data)
    }
    useEffect(() => {
        const timer = setInterval(() => {
            setCurrentTime(moment().format('YYYY年MM月DD日 HH:mm:ss'));
        }, 1000);
        let socketTimer: any
        const socket = new WebSocket('ws://47.111.161.238:8090/zhuzi/ws/server')
        socket.onopen = () => {
            console.log('open')
            clearInterval(socketTimer)
            socketTimer = setInterval(() => {
                socket.send(JSON.stringify({ heartBeat: new Date().valueOf() }))
            }, 60000)
        }
        socket.onmessage = (msg) => {
            console.log(msg)
            const data = JSON.parse(msg.data)
            if (data.messageType === 1) {
                const key = `open${Date.now()}`;
                const btn = (
                    <>
                        <Button className="mr10" type="primary" size="small" onClick={() => viewVideo(data.result)}>
                            详情
                        </Button>
                        <Button type="primary" size="small" onClick={() => notification.close(key)}>
                            取消
                        </Button>
                    </>
                );
                notification.open({
                    message: '报警通知',
                    description: <div>
                        <div>{moment().format('YYYY年MM月DD日 HH:mm:ss')}</div>
                        <div>
                            <EnvironmentOutlined className="mr5" />{data.result.areaName}
                        </div>
                        <div>{data.result.msg}</div>
                    </div>,
                    placement: 'bottomRight',
                    duration: 60 * 10,
                    btn,
                    key,
                });
            }
        }
        return () => {
            clearInterval(timer);
            clearInterval(socketTimer)
            socket.close()
        };
    }, []);
    /** 查询区域升降柱分组信息 */
    useEffect(() => {
        setCameras([]);
        if (selectedArea === -1) {
            getCameraAll().then((res) => {
                setCameras(res);
            });
        } else {
            getCamerasByArea({ areaId: selectedArea }).then((res) => {
                setCameras(res);
            });
            getLiftControlByAreaRun();
        }
    }, [selectedArea]);
    useEffect(() => {
        cameras?.map((camera) => {
            new window.Aliplayer({
                id: 'video' + camera.id,
                autoplay: true,
                source: camera.url || '//player.alicdn.com/video/aliyunmedia.mp4',
                width: '100%',
                height: '500px',
                isLive: true,
                rePlay: false,
                showBuffer: true,
                snapshot: false,
                showBarTime: 5000,
                useFlashPrism: true,
            });
        });
    }, [cameras]);
    /** 报警信息确认 */
    const checkAlarm = (alarm: IAlarm, status: number) => {
        checkAlarmApi({ id: alarm.id, status }).then(() => {
            message.success('操作成功')
            getAllAlarmsRun();
        });
    };
    return (
        <div className="home">
            <div className="mb10">时间：{currentTime}</div>
            <div className="flex">
                <Area selectedArea={selectedArea} setSelectedArea={setSelectedArea} ref={areaRef} />
                <div style={{ flex: 1 }}>
                    <div className="videos">
                        {cameras?.map((camera) => (
                            <div className="video-item" key={camera.id}>
                                <div className="video-title">
                                    {areaRef?.current?.areaNameMap[camera.areaId] + ' ' + camera.ipAddress}
                                </div>
                                <div className="video" id={'video' + camera.id}></div>
                            </div>
                        ))}
                    </div>

                    {selectedArea !== -1 && (
                        <LiftControl
                            selectedArea={selectedArea}
                            areaLiftLoading={areaLiftLoading}
                            areaLiftControl={areaLiftControl}
                            getLiftControlByAreaRun={getLiftControlByAreaRun}
                        />
                    )}
                    {
                        cameras?.length === 0 && <EmptyTip />
                    }
                </div>
                <div className="alarm-tag" onClick={() => setDrawerVisible(!drawerVisible)}>
                    报警列表
                </div>
                <Drawer
                    title={`异常报警列表(${alarmList?.length})`}
                    onClose={() => setDrawerVisible(false)}
                    visible={drawerVisible}
                    width={300}
                    closable={false}
                >
                    {alarmList?.map((alarm) => (
                        <Card className="alarm-card" key={alarm.id} hoverable>
                            <div className="mb10">{alarm.createDate}</div>
                            <div className="mb10">
                                <EnvironmentOutlined className="mr10" />
                                {alarm.areaName}
                            </div>
                            <div>异常详情: {alarm.msg}</div>
                            <div className="mt10">
                                <Button type="primary" size="small" className="mr10" onClick={viewVideo} >
                                    回放
                                </Button>
                                <Button className="mr10" size="small" onClick={() => checkAlarm(alarm, 1)}>
                                    确认
                                </Button>
                                <Button size="small" onClick={() => checkAlarm(alarm, -1)}>忽略</Button>
                            </div>
                        </Card>
                    ))}
                </Drawer>

            </div>
            <Modal
                title="异常回放"
                visible={abnormalVideoVisible}
                cancelText='退出'
                maskClosable={false}
                zIndex={9999}
                onCancel={() => setAbnormalVideoVisible(false)}
                onOk={() => setAbnormalVideoVisible(false)}
                destroyOnClose={true}
            >
                <video width="480" height="360"
                    src='//player.alicdn.com/video/aliyunmedia.mp4' controls autoPlay></video>
            </Modal>
        </div>
    );
};
export default providerHoc(reducer, initialReducer)(Home);
